package com.itic.mall.system.users.userstoken.service;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.mall.system.inter.users.userstoken.persistence.dao.UsersTokenDao;
import com.itic.mall.system.inter.users.userstoken.persistence.model.UsersToken;
import com.itic.mall.system.inter.users.userstoken.persistence.model.UsersTokenExample;
import com.itic.mall.system.inter.users.userstoken.persistence.model.UsersTokenExample.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Transactional
public class UsersTokenService
     extends CrudService<UsersTokenDao,UsersToken,UsersTokenExample> {
    @Autowired
    private UsersTokenDao usersTokenDao;

    //创建新的TOKEN，将之前的TOKEN设置失效
	public String addAndSyncOther(UsersToken createToken) {
		//将之前的TOKEN设置失效
		UsersTokenExample example = new UsersTokenExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andUserIdEqualTo(createToken.getUserId());
		criteria.andExpiredTimeGreaterThanOrEqualTo(new Date());//且没有过期
	    List<UsersToken> list = usersTokenDao.selectByExample(example);
		if( list.size()>0 ){
			//遍历所有有效的用户token，如果APPID一样就将之前的设置失效，不一样那么标识为异地登入
			for( UsersToken temp: list ){
				if( createToken.getAppId().equals(temp.getAppId()) ){
					temp.setIsEffective(DBConst.FALSE);
					usersTokenDao.updateByPrimaryKeySelective(temp);
				}else{
					temp.setIsOffsite(DBConst.TRUE);
					usersTokenDao.updateByPrimaryKeySelective(temp);
				}
			}
		}
		//添加新的TOKEN信息
		usersTokenDao.insert(createToken);
		return SUCCESS;
	}


}